package com.linln.admin.sync.controller;

import com.linln.admin.app.service.VersionService;
import com.linln.admin.sync.domain.FlowSql;
import com.linln.admin.sync.service.FlowSqlService;
import com.linln.admin.sync.validator.FlowSqlValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.actionLog.action.SaveAction;
import com.linln.component.actionLog.action.StatusAction;
import com.linln.component.actionLog.annotation.ActionLog;
import com.linln.component.actionLog.annotation.EntityParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author taofucheng
 * @date 2021/11/26
 */
@Controller
@RequestMapping("/sync/flowsql")
public class FlowSqlController {

    @Autowired
    private FlowSqlService flowSqlService;
    @Autowired
    private VersionService versionService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("sync:flowsql:index")
    public String index(Model model, FlowSql flowSql) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains())
                .withMatcher("content", match -> match.contains());

        // 获取数据列表
        Example<FlowSql> example = Example.of(flowSql, matcher);
        Page<FlowSql> list = flowSqlService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        model.addAttribute("versions", versionService.getAllDevVersions());
        model.addAttribute("versionId", flowSql.getVersion_id());
        return "/sync/flowsql/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("sync:flowsql:add")
    public String toAdd(Model model) {
        model.addAttribute("versions", versionService.getAllDevVersions());
        return "/sync/flowsql/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("sync:flowsql:edit")
    public String toEdit(@PathVariable("id") FlowSql flowSql, Model model) {
        model.addAttribute("flowSql", flowSql);
        model.addAttribute("versions", versionService.getAllDevVersions());
        return "/sync/flowsql/add";
    }

    /**
     * 保存添加/修改的数据
     *
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"sync:flowsql:add", "sync:flowsql:edit"})
    @ResponseBody
    @ActionLog(name = "上线SQL管理", message = "应用：${title}", action = SaveAction.class)
    public ResultVo save(@Validated FlowSqlValid valid, @EntityParam FlowSql flowSql) {
        // 复制保留无需修改的数据
        if (flowSql.getId() != null) {
            FlowSql beFlowSql = flowSqlService.getById(flowSql.getId());
            EntityBeanUtil.copyProperties(beFlowSql, flowSql);
        }

        // 保存数据
        flowSqlService.save(flowSql);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("sync:flowsql:detail")
    public String toDetail(@PathVariable("id") FlowSql flowSql, Model model) {
        model.addAttribute("flowSql", flowSql);
        model.addAttribute("versions", versionService.getAllDevVersions());
        return "/sync/flowsql/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("sync:flowsql:status")
    @ResponseBody
    @ActionLog(name = "上线SQL状态", action = StatusAction.class)
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (flowSqlService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }


    /**
     * 跳转到同步页面
     */
    @GetMapping("/sync")
    @RequiresPermissions("sync:flowsql:sync")
    public String toSync(Model model) {
        return "/sync/flowsql/sync";
    }

    /**
     * 同步操作
     *
     * @param combinePubEnv 要同步到哪个环境
     */
    @PostMapping("/sync")
    @RequiresPermissions("sync:flowsql:sync")
    @ResponseBody
    @ActionLog(name = "同步上线SQL", message = "将所有已上线的SQL同步到${combinePubEnv}环境中")
    public ResultVo toSync(String combinePubEnv) {
        if (StringUtils.isBlank(combinePubEnv)) {
            return ResultVoUtil.error("请先选择要同步到哪个环境");
        }

        // 保存数据
        try {
            return ResultVoUtil.success("成功", flowSqlService.sync(combinePubEnv));
        } catch (Exception e) {
            return ResultVoUtil.error("同步失败！" + e);
        }
    }
}